package com.study.webapp.jdk8;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * @program: study
 *
 * @description:
 *
 * @author: heqiang
 *
 * @create: 2020-04-24 17:46
 **/
public class CountDownLatchTest {

    private static final int RUNNER = 5;

    private static final Random random = new Random();


    public static void main(String[] args) {
        CountDownLatch ready = new CountDownLatch(RUNNER);
        CountDownLatch start = new CountDownLatch(1);
        for (int i = 0; i<RUNNER;i++) {
            Thread thread = new Thread(new MyRunner("haha"+i,ready,start));
            thread.start();
        }

        try {
            ready.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        start.countDown();
        System.out.println("准备完毕，开始。。。。。");

    }

    static class MyRunner implements Runnable {
        private CountDownLatch ready;
        private String name;
        private CountDownLatch start;

        public MyRunner(String name,CountDownLatch ready,CountDownLatch start) {
            this.ready = ready;
            this.start = start;
            this.name = name;
        }

        @Override
        public void run() {
            int readyTime = random.nextInt(1000);
            System.out.println(name+":我需要"+readyTime+"准备");
            try {
                Thread.sleep(readyTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name+":准备好了");
            ready.countDown();
            try {
                start.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name+":开始------");
        }
    }
}
